import urllib2
import os
import cookielib

COOKIEFILE = 'cookies.lwp'

urlopen = urllib2.urlopen
Request = urllib2.Request
cj = cookielib.LWPCookieJar()

if os.path.isfile(COOKIEFILE):
    cj.load(COOKIEFILE)

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)


theurl = 'http://kanji.koohii.com/status/export_stories.php'
#http://kanji.koohii.com/login.php
#values = {'uname' : 'Pants_Magoo','passwd' : 'xxxxxxx','remember':'1','submit':'Login'}
data = None#urllib.urlencode(values)

txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
# fake a user agent, some websites (like google) don't like automated exploration

try:
    req = Request(theurl, data, txheaders)
    # create a request object

    handle = urlopen(req)
    # and open it to return a handle on the url

except IOError, e:
    print 'We failed to open "%s".' % theurl
    if hasattr(e, 'code'):
        print 'We failed with error code - %s.' % e.code
    elif hasattr(e, 'reason'):
        print "The error object has the following 'reason' attribute :"
        print e.reason
        print "This usually means the server doesn't exist,"
        print "is down, or we don't have an internet connection."
    sys.exit()

else:
    print 'Here are the headers of the page : '+str(handle.geturl())
    print
    print handle.info()
    # handle.read() returns the page
    # handle.geturl() returns the true url of the page fetched
    # (in case urlopen has followed any redirects, which it sometimes does)

print
if cj is None:
    print "We don't have a cookie library available - sorry."
    print "I can't show you any cookies."
else:
    print 'These are the cookies we have received so far :'
    for index, cookie in enumerate(cj):
        print index, '  :  ', cookie
    cj.save(COOKIEFILE)

def filize():
    outputFile = open('zzztop.txt',"wb")
    for x in handle.read():
        outputFile.write(x)
    outputFile.close()
filize()